#include "stdafx.h"
#include "ISort2.h"
#include "MyClassFactory.h"

MyClassFactory ClassFactory;
volatile LONG LockCount;
volatile LONG OutstandingObjects;

HRESULT STDMETHODCALLTYPE MyClassFactory::QueryInterface(REFIID riid, void **ppv)
{
    if (IsEqualIID(riid, IID_IUnknown) ||
        IsEqualIID(riid, IID_IClassFactory))
    {
        *ppv = this;
        AddRef();
        return S_OK;
    }

    *ppv = NULL;
    return E_NOINTERFACE;
}

ULONG STDMETHODCALLTYPE MyClassFactory::AddRef()
{
    return 1;
}

ULONG STDMETHODCALLTYPE MyClassFactory::Release()
{
    return 1;
}

HRESULT STDMETHODCALLTYPE MyClassFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject)
{
    if (pUnkOuter != NULL)
    {
        *ppvObject = NULL;
        return CLASS_E_NOAGGREGATION;
    }

    MyISort *pObj = new MyISort;
    if (pObj == NULL) return E_OUTOFMEMORY;

    HRESULT hr = pObj->sort.QueryInterface(riid, ppvObject);
    pObj->sort.Release();
    if (SUCCEEDED(hr)) InterlockedIncrement(&OutstandingObjects);
    return hr;
}

HRESULT STDMETHODCALLTYPE MyClassFactory::LockServer(BOOL fLock)
{
    if (fLock) InterlockedIncrement(&LockCount);
    else InterlockedDecrement(&LockCount);
    return S_OK;
}
